package org.osm2world.core.osm.creation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.osm2world.core.osm.data.OSMData;

/**
 * DataSource providing information from a single .osm file, including common
 * non-standard variants such as those files produced by JOSM. The file is read
 * during the {@link #getData()} call, there will be no updates when the file is
 * changed later. This class internally uses Osmosis to read the file.
 * 
 * At its core, this reader combines the capabilities of the {@link OSMFileReader}
 * and the {@link JOSMFileReader}.
 */
public class OSMFileReader implements OSMDataReader {

	private final File file;
	
	public OSMFileReader(File file) throws FileNotFoundException {
		this.file = file;
		if (!file.exists()) {
			throw new FileNotFoundException(file.toString());
		}
	}
	
	@Override
	public OSMData getData() throws IOException {
		
		OSMData osmData = null;
		boolean useJOSMReader = false;
		
		if (isJOSMGenerated(file)) {
			useJOSMReader = true;
		} else {
			
			/* try to read file using Osmosis */
			
			try {
				osmData = new StrictOSMFileReader(file).getData();
			} catch (IOException e) {
				
				System.out.println("could not read file," +
						" trying workaround for files created by JOSM");
				
				useJOSMReader = true;
							
			}
			
		}
		
		/* try reading the file while taking into account JOSM-specific extensions */
		
		if (useJOSMReader) {
			
			try {
				osmData = new JOSMFileReader(file).getData();
			} catch (Exception e2) {
				throw new IOException("could not read OSM file" +
						" (not even with workaround for JOSM files)", e2);
			}
	
		}
		
		return osmData;
			
	}
	
	/**
	 * Returns true if the file was identified as being generated by JOSM.
	 * This method peeks into the first lines of the file,
	 * trying to find the generator tag.
	 */
	public static final boolean isJOSMGenerated(File file) {
		
		try {
			
			BufferedReader reader = new BufferedReader(new FileReader(file));
			
			for (int i=0; i<100; i++) {
				String line = reader.readLine();
				if (line != null) {
					if (line.contains("generator='JOSM'")) {
						return true;
					}
				}
			}
			
			reader.close();
			
		} catch (IOException e) { }
		
		return false;
		
	}

}
